package com.suneast.suneaststore.modules.personal.sign;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.suneast.suneaststore.R;
import com.suneast.suneaststore.modules.personal.sign.event.CountDownEvent;
import com.suneast.suneaststore.modules.common.Flag;
import com.suneast.suneaststore.modules.personal.sign.event.RequestAutoCodeResult;
import com.suneast.suneaststore.modules.personal.sign.event.ResetPwdResult;
import com.suneast.suneaststore.ui.fragments.BaseFragment;
import com.suneast.suneaststore.util.regex.RegexUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.OnClick;

public class ResetPwdFragment extends BaseFragment {
    @Override
    public int setLayout() {
        return R.layout.fragment_reset_password;
    }

    @Override
    public void onBindView(@Nullable Bundle savedInstanceState, @NonNull View rootView) {
        EventBus.getDefault().register(this);
        initView();
    }

    @Override
    public void onDestroyView() {
        timer.cancel();
        task.cancel();
        EventBus.getDefault().unregister(this);
        super.onDestroyView();
    }

    @BindView(R.id.toolbar)
    Toolbar toolbar;

    @OnClick({R.id.btn_request_code, R.id.btn_confirm})
    public void onViewClick(View view) {
        switch (view.getId()) {
            case R.id.btn_request_code: {
                if (RegexUtil.isMobile(phoneNumber)) {
                    SignRequestHandler.requestAuthCode(phoneNumber, Flag.CodeType.RESET);
                    requestCodeBtn.setEnabled(false);
                } else {
                    Toast.makeText(getContext(), "请输入正确的手机号", Toast.LENGTH_SHORT).show();
                }
            }
            break;
            case R.id.btn_confirm: {
                if (phoneNumber.length() == 11) {
                    if (authCode.length() == 4) {
                        if (password.length() >= 6) {
                            if (password.equals(confirmPassword)) {
                                Log.e("test", "onViewClick: number = " + phoneNumber +
                                        " authcode = " + authCode + " password = " + password);
                                SignRequestHandler.resetPwd(phoneNumber, authCode, password,confirmPassword);
                            } else {
                                Toast.makeText(getContext(), "两次输入密码不一致", Toast.LENGTH_SHORT).show();
                            }
                        } else {
                            Toast.makeText(getContext(), "请输入6位长度及以上的密码", Toast.LENGTH_SHORT).show();
                        }
                    } else {
                        Toast.makeText(getContext(), "请输入4位数字的验证码", Toast.LENGTH_SHORT).show();
                    }
                } else {
                    Toast.makeText(getContext(), "请输入正确的手机号", Toast.LENGTH_SHORT).show();
                }
            }
            break;
        }
    }

    @BindView(R.id.et_phone_number)
    EditText phoneNumberEt;

    @BindView(R.id.et_auth_code)
    EditText authCodeEt;

    @BindView(R.id.et_set_password)
    EditText newPasswordEt;

    @BindView(R.id.et_confirm_password)
    EditText confirmNewPasswordEt;

    @BindView(R.id.btn_request_code)
    Button requestCodeBtn;

    @BindView(R.id.btn_confirm)
    Button confirmBtn;

    private String phoneNumber = "";
    private String authCode = "";
    private String password = "";
    private String confirmPassword = "";

    private Timer timer;
    private TimerTask task;

    private void initView() {
        toolbar.setNavigationOnClickListener(v -> pop());
        timer = new Timer();
        task = new TimerTask() {
            @Override
            public void run() {
                EventBus.getDefault().post(new CountDownEvent(Flag.CodeType.RESET));
            }
        };
        phoneNumberEt.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                phoneNumber = s.toString();
            }
        });
        authCodeEt.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                authCode = s.toString();
            }
        });
        newPasswordEt.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                password = s.toString();
            }
        });
        confirmNewPasswordEt.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                confirmPassword = s.toString();
            }
        });
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onResetResult(ResetPwdResult result) {
        switch (result.getResult()) {
            case Flag.Result.SUCCEED: {
                Toast.makeText(getContext(), "重置密码成功,请重新登录", Toast.LENGTH_SHORT).show();
                pop();
            }
            break;
            case Flag.Result.FAILURE: {
                if (result.getMsg() != null) {
                    Toast.makeText(getContext(), "重置密码失败 " + result.getMsg(), Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(getContext(), "重置密码失败", Toast.LENGTH_SHORT).show();
                }
            }
            break;
        }
    }

    private int count = 90;

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onCountDown(CountDownEvent event) {
        if (event.getType() == Flag.CodeType.RESET) {
            if (count > 0) {
                requestCodeBtn.setText(count + getResources().getString(R.string.afresh_auto_code));
                count--;
            } else {
                task.cancel();
                requestCodeBtn.setEnabled(true);
                requestCodeBtn.setText(getResources().getString(R.string.get_auth_code));
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onRequestAuthCodeResult(RequestAutoCodeResult event) {
        if (event.getState() == Flag.Result.SUCCEED) {
            count = 90;
            timer.schedule(task, 0, 1000);
        } else if (event.getState() == Flag.Result.FAILURE) {
            requestCodeBtn.setEnabled(true);
            Toast.makeText(getContext(), "请求验证码失败", Toast.LENGTH_SHORT).show();
        }
    }
}

